# -*- coding: utf-8 -*- # 
from xml.dom import minidom
import sys
import os
import types
def lupper(str):
    if str != None and len(str)>0:
        return "%s%s" %(str[0:1].upper(),str[1:len(str)].lower())
    return str
#中文字体
def nodTable(content,par = None,fullname = ""):
    if content == None :
       content =  self.xmlContent
    if par == None :
       par =  {}

    childs = len(content.childNodes)
    wktable = par
    for node in content.childNodes:
        tablename = "" 
        name = node.nodeName
        if name == "xs:element" or name == "xs:attribute" :
            tablename = node.attributes['name'].value
            wktable[tablename]={}
            setColum(node,wktable[tablename], "type")
            setColum(node,wktable[tablename], 'use')
            setColum(node,wktable[tablename], 'minOccurs')
            setColum(node,wktable[tablename], 'maxOccurs')
            wktable[tablename][".attribute"]["name"] = tablename
            wktable =wktable[tablename]
            #print "%d:%s"%(self.step,self.alltable)

        nodTable(node,wktable,fullname+lupper(tablename))

        if name =="xs:element" or name == "xs:attribute":
            if len(wktable)>1:
                wktable[".attribute"]["type"] = "Table"
                wktable[".attribute"]["name"]=fullname+lupper(tablename)
            wktable=par
                
    #if(childs > 1 and (content.nodeName== "xs:element" or content.nodeName == "xs:attribute") ):
        #self.wktable = par
    #    pass
    return par

def printDic(dic,step=0):
    keys = sorted(dic.keys())
    
    fix = "  "
    for key in keys:
        obj = dic[key]
        if type(obj) == types.DictionaryType:
            print  "%s%s" %((fix*step),key)
            printDic(obj,step+1)
        else:
            print "%s%s:%s" %(fix*step,key,obj)

def setColum(node,dict,colName):
    if dict.has_key(".attribute") :
        pass
    else:
        dict[".attribute"] = {}
    if node.hasAttribute(colName) :
        dict[".attribute"][colName] = node.attributes[colName].value
    else:
        dict[".attribute"][colName] = ""
        
class xmlData:
    pass
class xmlPaser:
    def __init__(self,path):
        self.filePath = path
    
    def parse(self):
        self.xmlContent = minidom.parse( self.filePath )
    def nodTable(content = None):
       if content == None :
          content =  self.xmlContent
       childs = len(content.childNodes)
       colDic = {}
       for node in content.childNodes:
           tablename = "" 
           name = node.nodeName
           if len(node.childNodes)>0 :
               colDic[name] = self.nodTable(node)
               pass
           else:
               colDic[name] = node.data
       return colDic


class xsdParser:
    step = 0
    def __init__(self,path):
        self.filePath = path
        self.alltable = {}
        self.wktable = self.alltable
    
    def parse(self):
        self.xmlContent = minidom.parse( self.filePath )
    def printContent(self,encode = 'UTF-8'):
        print self.xmlContent.toxml(encoding = encode)

    def toDB(self,dbname=None):
        if(dbname == None):
            dbname = self.filePath.split('/')[-1] + ".xmldb"
        print dbname
        from dbProcessor import dbProcessor
        #dbname = tableDic.keys()[0]
        dbprocess = dbProcessor(dbname)
        dbprocess.delAllTable()
        
        tableDic = nodTable(self.xmlContent)
        (sqlList,colList) = self.toSQL(tableDic)
        print '\n'.join(sqlList)
        for sql in sqlList:
            print sql
            dbprocess.executeSQL(sql)
        dbprocess.close()
        pass
    def toSQL(self,inDic):
        keys = sorted(inDic.keys())
        
        sqlList = []
        colList = []
        parent = ""
        if ".attribute" in keys:
            parent = inDic[".attribute"]["name"]
        for colname in keys:
            sqlstr = ""
            if colname == ".attribute":
                continue 
            contentDic = inDic[colname]
            attrDic = contentDic[".attribute"]
            if attrDic["type"] == "Table":
                sqlstr = "create table '%s' ( %s )"
                (reSqlList,reColList) = self.toSQL(contentDic)
                if len(reSqlList) > 0:
                    sqlList.extend(reSqlList)
                if len(reColList) == 0:
                    reColList.append("'%s' %s" %(colname,"Text"))
                if parent != "":
                    reColList.insert(0,"'%s' %s" %("fk"+parent,"Integer"))
                reColList.insert(0,"'%s' %s" %("pk"+contentDic[".attribute"]["name"],"Integer"))
                reColList.append("PRIMARY KEY (pk%s AUTOINCREMENT)" % contentDic[".attribute"]["name"])
                sqlstr = sqlstr % (contentDic[".attribute"]["name"],",".join(reColList))
                sqlList.append(sqlstr)
            else:
                colList.append("'%s' %s" %(colname,"Text"))
                pass
        return (sqlList,colList)

    def toZodb(self,content=None, path = None):
        from ZODB import FileStorage,DB
        import transaction
        if content == None :
           content =  self.xmlContent
        self.storage = FileStorage.FileStorage("./xsd.zodb")
        self.db = DB(self.storage)
        self.connection = self.db.open()
        self.dbroot = self.connection.root()
        
    def close(self):
        if(self.connection):
            self.connection.close()
        if self.db:
            self.db.close()
        if self.storage:
            self.storage()
        
        
from UserDict import UserDict
from UserList import UserList

class tableData(UserList):
    def __init__(self, tname=None):
        UserList.__init__(self)
        self[0] = tname

class columnData(UserDict):
    def __init__(self, cname=None):
        UserDict.__init__(self)
        self["name"] = cname
    def setType(self,type="String",pkey = False,):
        self["Type"] = type
        if(type == "String"):
            pass
        elif type == "boolean":
            pass
        elif type == "short":
            pass
        elif type == "Table":
            pass
        

xmlp = xmlPaser(r"/media/sda2/Tools/OfflineList/datas/ADVANsCEne_NDS.xml")
xsdp = xsdParser(r"/media/sda2/Tools/OfflineList/datas/datas.xsd")

#xsdp = xsdParser(r"D:\wangzw\tool\eclipse-java-europa-winter-win32\eclipse\workspace\pyromlist\datas.xsd")
#xsdp = xsdParser(r"D:\wangzw\tool\eclipse-java-europa-winter-win32\eclipse\workspace\pyromlist\tmp.xsd")
xsdp.parse()
xmlp.parse()
#xsdp.nodTable()

#tableDic =  nodTable(xsdp.xmlContent)
#printDic(tableDic)
printDic(xmlp.nodTable())
#xsdp.toDB()
#print xmlp.alltable["dat"]["configuration"].keys()
#print ",".join(xmlp.alltable["dat"].keys()).encode("UTF8")
#print ",".join(xmlp.alltable["dat"]["configuration"].keys()).encode("UTF8")
#print ",".join(xmlp.alltable["dat"]["configuration"]["infos"].keys()).encode("UTF8")
#print ",".join(xmlp.alltable["dat"]["configuration"]["infos"]["title"].keys()).encode("UTF8")
#print xmlp.alltable["dat"]["configuration"]["infos"][".attribute"]
#print ",".join(xmlp.alltable["dat"]["gui"].keys()).encode("UTF8")
#print ",".join(xmlp.alltable["dat"]["games"]["game"].keys()).encode("UTF8")
#sqlList = xsdp.dicToSQL(xsdp.alltable,start=True)

#sqlList = xsdp.dicToDB(xsdp.alltable)

#firstcode = xmlp.xmlContent.firstChild
#print firstcode.toxml(encoding='UTF-8')
